//
//  MyHelpAndTopicViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/6/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "MyHelpAndTopicViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "LinLi.h"
#import "HelpTextViewController.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "ConvertToCommonEmoticonsHelper.h"
//#import "LinLiTableViewCell.h"
#import "MWPhotoBrowser.h"
#import "PeopleDataViewController.h"
#import "MaxResponseButton.h"
#import "TTTAttributedLabel.h"
#import "VillageTableViewCell.h"

@interface MyHelpAndTopicViewController ()<MWPhotoBrowserDelegate>{
    
    float imgWidth;
    NSMutableArray *helpListArray,*photos;
    int contentPage;
    NSInteger currentDelectRow;
    LinLi *currentLinLi;
    NSIndexPath *selectedIndexPath;
}

@end

@implementation MyHelpAndTopicViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title=@"我的乡情";
    contentPage=1;
    imgWidth=ceilf((ScreenWidth-40)/3.0);
    helpListArray=[[NSMutableArray alloc]init];
    
    [self createNavButton];
    [self createTableView];
    [self getHelpListInfoWithPage:1 andIsRefresh:YES];
    [self addRefreshAttribute];
    //监听我的乡情变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMyVillageTableView:) name:@"reloadMyVillageTableView" object:nil];
}

-(void)createTableView{
    
    _myHelpTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64) style:UITableViewStyleGrouped];
    _myHelpTableView.dataSource=self;
    _myHelpTableView.delegate=self;
    _myHelpTableView.backgroundColor=[UIColor whiteColor];
    _myHelpTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_myHelpTableView];
}

-(void)createNavButton{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
}

- (void)addRefreshAttribute{
    
    __weak typeof(self) weakSelf = self;
    
    [self.myHelpTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    [self.myHelpTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

- (void)reloadDataToNew:(BOOL)new{
    
    if (new) {
        contentPage=1;
        [self getHelpListInfoWithPage:1 andIsRefresh:new];
    }else{
        contentPage=contentPage+1;
        [self getHelpListInfoWithPage:contentPage andIsRefresh:new];
    }
}

-(void)getHelpListInfoWithPage:(int)page andIsRefresh:(BOOL)isRefresh{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"op_topic_help_list.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [self.myHelpTableView.legendHeader endRefreshing];
        [self.myHelpTableView.legendFooter endRefreshing];
        
        if (![[result objectForKey:@"response"] isEqualToString:@"op_topic_help_list"]) {
            
            [Config showHUDWithText:@"获取乡情失败!" andImage:@"error"];
            return ;
        }
        
        NSDictionary *dic=[result objectForKey:@"data"];
        NSArray *listArray=[dic objectForKey:@"list"];
        
        if (listArray.count==0) {
            
            if (!isRefresh) {
                contentPage=contentPage-1;
                [Config showHUDWithText:@"没有更多数据" andImage:@"done"];
            }
            [self.myHelpTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            return ;
        }
        
        if (isRefresh) {
            [helpListArray removeAllObjects];
        }
        for (NSDictionary *dic in listArray) {
            //LinLi *linli=[[LinLi alloc]initWithDictionary:dic];
            LinLi *linli=[LinLi yy_modelWithDictionary:dic];
            NSString *contentText = [ConvertToCommonEmoticonsHelper
                                     convertToSystemEmoticons:linli.introduce];
            linli.contentHeight=[self heightWithString:contentText];
            linli.introduce=contentText;
            [helpListArray addObject:linli];
        }
        [self.myHelpTableView reloadData];
        
    }failureAction:^{
        [self.myHelpTableView.legendHeader endRefreshing];
        [self.myHelpTableView.legendFooter endRefreshing];
    }];
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectio{
    
    return helpListArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectio{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LinLi *linLi=[helpListArray objectAtIndex:indexPath.row];
    //NSString *contentText = [ConvertToCommonEmoticonsHelper convertToSystemEmoticons:linLi.introduce];
    float cellHeight;
    if (linLi.contentHeight>150) {
        cellHeight=180+115;
    }else{
        cellHeight=linLi.contentHeight+115;
    }
    if (linLi.pics.count>0) {
        
        if (linLi.pics.count==1) {
            float height=[self onePicHeightWithWidth:linLi.first_pic_width andHeight:linLi.first_pic_height];
            cellHeight=cellHeight+height+10;
        }else{
            cellHeight=cellHeight+(linLi.pics.count+2)/3*(imgWidth+5);
        }
    }
    return cellHeight;
}

-(float)onePicHeightWithWidth:(float)width andHeight:(float)height{
    
    float picHeight;
    if (width<ScreenWidth-30&&height<250) {
        picHeight=height;
    }else{
        if(width>ScreenWidth-30&&height<250) {
            picHeight=(ScreenWidth-30)*height/width;
        }else if(width<ScreenWidth-30&&height>250){
            picHeight=250;
        }else if(width>ScreenWidth-30&&height>250){
            picHeight=(ScreenWidth-30)*height/width;
        }else{
            picHeight=imgWidth;
        }
    }
    return ceilf(picHeight);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier=@"cell";
    LinLi *linLi=[helpListArray objectAtIndex:indexPath.row];
    
    VillageTableViewCell *cell =(VillageTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    if (!cell) {
        cell = [[VillageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier andLinLi:linLi andRange:1];
    }
    if (linLi.type==1) {
        [cell.helpLabel removeFromSuperview];
    }
    
    cell.selectedIndexPath=indexPath;
    cell.goToPersonInfo=^(NSInteger currentRow){
        //查看个人信息
        [self lookPersonInfo:currentRow];
    };
    cell.addLike=^(NSInteger currentRow){
        //点赞
        [self praiseButtonClick:currentRow];
    };
    cell.checkBigPics=^(NSInteger currentRow,NSInteger currentPage){
        //点击图片
        [self checkBigPicWithCurrentRow:currentRow andCurrentPage:currentPage];
    };
    
    MaxResponseButton *delectInfoBtn=[MaxResponseButton buttonWithType:UIButtonTypeCustom];
    delectInfoBtn.frame=CGRectMake(ScreenWidth-35, 15, 23, 23);
    delectInfoBtn.tag=indexPath.row;
    [delectInfoBtn setBackgroundImage:[UIImage imageNamed:@"deletemytopic.png"] forState:UIControlStateNormal];
    [delectInfoBtn addTarget:self action:@selector(delectInfo:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:delectInfoBtn];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    selectedIndexPath=indexPath;//记录当前点击区
    LinLi *linLi=[helpListArray objectAtIndex:indexPath.row];
    HelpTextViewController *textVC=[[HelpTextViewController alloc]init];
    textVC.linLi=linLi;
    textVC.type=1;
    [self.navigationController pushViewController:textVC animated:YES];
}

-(float)heightWithString:(NSString *)introduce{
    
    CGRect rect = [introduce boundingRectWithSize:CGSizeMake(ScreenWidth-30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]} context:nil];
    CGFloat height = ceilf(rect.size.height);
    return height + 15 ;
}

-(void)delectInfo:(UIButton *)btn{
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    currentLinLi=[helpListArray objectAtIndex:btn.tag];
    currentDelectRow=btn.tag;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==1) {
        
        NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
        [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
        [CheckParams setObject:currentLinLi.itemid forKey:@"itemid"];
        [CheckParams setObject:[NSString stringWithFormat:@"%d",currentLinLi.type+2] forKey:@"type"];
        NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
        [CheckParams setObject:resultSign forKey:@"sign"];
        [MyDataService requestURL:@"del_article.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
            
            NSLog(@"%@",result);
            if ([[result objectForKey:@"response"] isEqualToString:@"del_article"]) {
                
                [Config showHUDWithText:@"删除成功!" andImage:@"done"];
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:currentDelectRow inSection:0];
                [helpListArray removeObjectAtIndex:indexPath.row];
                [_myHelpTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [_myHelpTableView reloadData];
                });
                
            }else{
                
                [Config showHUDWithText:@"删除失败!" andImage:@"error"];
                return ;
            }
            
        }failureAction:^{
            [Config showHUDWithText:@"删除失败!" andImage:@"error"];
        }];
    }
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 浏览大图

-(void)checkBigPicWithCurrentRow:(NSInteger)currentRow andCurrentPage:(NSInteger)currentPage{
    
    LinLi *linLi=[helpListArray objectAtIndex:currentRow];
    photos = [NSMutableArray array];
    for (NSString *urlString in linLi.big_pics) {
        [photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlString]]];
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.isScrollerPic=YES;
    [browser setCurrentPhotoIndex:currentPage];
    [self.navigationController pushViewController:browser animated:YES];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < photos.count) {
        return [photos objectAtIndex:index];
    }
    return nil;
}

#pragma mark - 查看个人信息

-(void)lookPersonInfo:(NSInteger)currentRow{
    
    LinLi *linLi=[helpListArray objectAtIndex:currentRow];
    PeopleDataViewController *dataVC=[[PeopleDataViewController alloc]init];
    dataVC.touserid=linLi.userid;
    dataVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:dataVC animated:YES];
}

#pragma mark - 点赞

-(void)praiseButtonClick:(NSInteger)currentRow{
    
    LinLi *linli=[helpListArray objectAtIndex:currentRow];
    NSString *urlString=linli.is_prase==0?@"topicpraise.php":@"cancel_prase.php";
    NSString *responseString=linli.is_prase==0?@"topicpraise":@"cancel_prase";
    NSString *remaindString=linli.is_prase==0?@"点赞成功":@"取消赞成功";
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject: linli.itemid forKey:@"itemid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",linli.type] forKey:@"type"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:urlString httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:responseString]) {
            
            [Config showHUDWithText:remaindString andImage:@"done"];
            //改变点赞行的赞个数
            if (linli.is_prase==0) {
                linli.is_prase=1;
                linli.look=linli.look+1;
            }else{
                linli.is_prase=0;
                linli.look=linli.look-1;
            }
            [helpListArray replaceObjectAtIndex:currentRow withObject:linli];
            VillageTableViewCell *linliCell =(VillageTableViewCell *)[_myHelpTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:0]];
            [linliCell reloadPraiseWithLinLi:linli];
            
        }else{
            
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                [Config showHUDWithText:str andImage:@"error"];
            }else{
                [Config showHUDWithText:@"操作失败!" andImage:@"error"];
            }
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"网络错误!" andImage:@"error"];
    }];
}

-(void)reloadMyVillageTableView:(NSNotification *)text{
    
    NSLog(@">>>>>>>我的乡情变化>>>>>>>%@",text.userInfo);
    
    if (text.userInfo[@"content"]) {
        
        [helpListArray replaceObjectAtIndex:selectedIndexPath.row withObject:text.userInfo[@"content"]];
        VillageTableViewCell *linliCell =(VillageTableViewCell *)[_myHelpTableView cellForRowAtIndexPath:selectedIndexPath];
        if ([text.userInfo[@"name"] isEqualToString:@"praiseChange"]) {
            [linliCell reloadPraiseWithLinLi:text.userInfo[@"content"]];
        }else{
            [linliCell reloadCommentCountWithLinLi:text.userInfo[@"content"]];
        }
        
    }else{
        
        //当前乡情被删除
        [helpListArray removeObjectAtIndex:selectedIndexPath.row];
        [_myHelpTableView deleteRowsAtIndexPaths:@[selectedIndexPath] withRowAnimation:UITableViewRowAnimationRight];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_myHelpTableView reloadData];
        });
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadMyVillageTableView" object:nil];
}

@end
